package com.pes.arcww.dao;

import java.util.Collection;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.pes.arcww.form.Exams;
import com.pes.arcww.form.ExamsItems;

@Repository
public class ExamsDAOImpl implements ExamsDAO{

	@Autowired
	private SessionFactory sessionFactory;
	
	public void addExam(Exams exam) {
		sessionFactory.getCurrentSession().save(exam);
	}
	
	public void addExamsItems(Integer exa_id, ExamsItems item) {
		Exams exam = getExam(exa_id);
		item.setExam(exam);
		sessionFactory.getCurrentSession().save(item);
	}

	@SuppressWarnings("unchecked")
	public Collection<Exams> listExams(String filter, String value) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(Exams.class);
		
		if(filter.equals("") && value.equals("")){
			criteria.addOrder(Order.desc("exa_id"));
		}else if(filter.equals("id")){
			criteria.add(Restrictions.sqlRestriction(" exa_id LIKE '%"+value+"%' ")).addOrder(Order.desc("exa_id"));
		}else if(filter.equals("title")){
			criteria.add(Restrictions.like("title", "%"+value+"%")).addOrder(Order.asc("title"));
		}else{//description
			criteria.add(Restrictions.like("description", "%"+value+"%")).addOrder(Order.asc("description"));
		}

		return criteria.list();
		
	}

	public void removeExam(Integer id) {
		Exams exam = getExam(id);
		if(exam != null){
			sessionFactory.getCurrentSession().delete(exam);
		}
	}

	public void updateExam(Exams exam) {
		sessionFactory.getCurrentSession().update(exam);
	}

	public Exams getExam(Integer id) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Exams exam = (Exams) session.get(Exams.class, id);
		Hibernate.initialize(exam.getProfile()); 
		Hibernate.initialize(exam.getUser()); 
		Hibernate.initialize(exam.getExamItemsList()); 
		session.getTransaction().commit();
		session.close();
		
		return exam;
	}
}
